package cfdt.ldl.signatrue.util;

import java.security.MessageDigest;

import cfdt.common.enums.CommonCodeEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cfdt.common.exception.CodeException;
import cfdt.tools.util.StringUtils;

/**
 * 消息签名 SHA1Util class
 *
 * @author CPYF-Yi Mao
 */
public final class Sha1Utils {
    private static final Logger logger = LoggerFactory.getLogger("Sha1Utils");
    private Sha1Utils() {
    }

    /**
     * 用SHA1算法生成安全签名
     */
    public static String hash(String str) throws CodeException {
        try {

            // SHA1签名生成
            MessageDigest md = MessageDigest.getInstance("SHA-1");
            md.update(str.getBytes(StringUtils.DEFAULT_CHARSET));
            byte[] digest = md.digest();

            StringBuilder hexStr = new StringBuilder();
            String shaHex;
            for (byte aDigest : digest) {
                shaHex = Integer.toHexString(aDigest & 0xFF);
                if (shaHex.length() < 2) {
                    hexStr.append(0);
                }
                hexStr.append(shaHex);
            }
            return hexStr.toString();

        } catch (Exception e) {
            logger.error("SHA1签名生成失败",e);
            throw new CodeException(CommonCodeEnum.CODE_2407);
        }
    }
}
